﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using System.Windows;
using System.Diagnostics;
using System.Collections.ObjectModel;
using Microsoft.Win32;
using System.IO;

namespace MedicalInterface.ViewModel
{
    public class AddObsViewModel : BaseViewModel
    {
        #region variables
        private bool _closeSignal;
        private ObservationServiceReference.ServiceObservationClient serviceObservationClient;
        private ObservationServiceReference.Observation obs;
        private PatientServiceReference.Observation obs2;
        private PatientServiceReference.Patient _patient;
        private ObservableCollection<string> _prescriptions;
        private ObservableCollection<Byte[]> _images;

        private int _bloodPressure;
        private string _comment;
        private int _weight;

       
        #endregion

        #region commandes
        private ICommand _cmd_ok;
        private ICommand _addPrescCommand;
        private ICommand _addImgCommand;
        #endregion

        private bool CanCommandExecute(object parameter)
        {
            return true;
        }

        #region getter / setter

        /// <summary>
        /// Prescription du patient
        /// </summary>
        public ObservableCollection<Byte[]> Images
        {
            get { return _images; }
            set { _images = value; }
        }
        
        /// <summary>
        /// Prescription du patient
        /// </summary>
        public ObservableCollection<string> Prescriptions
        {
            get { return _prescriptions; }
            set { _prescriptions = value; }
        }

        /// <summary>
        /// command pour OK
        /// </summary>
        public ICommand cmd_ok
        {
            get
            {
                if (_cmd_ok == null)
                {
                    _cmd_ok = new RelayCommand(Confirm, CanOk);
                }
                return _cmd_ok;
            }
            set { _cmd_ok = value; }
        }

        /// <summary>
        /// commande pour ajouter une prescription
        /// </summary>
        public ICommand AddImgCommand
        {
            get
            {
                if (_addImgCommand == null)
                {
                    _addImgCommand = new RelayCommand(NewImg, CanCommandExecute);
                }
                return _addImgCommand;
            }
            set { _addImgCommand = value; }
        }

        /// <summary>
        /// commande pour ajouter une prescription
        /// </summary>
        public ICommand AddPrescCommand
        {
            get
            {
                if (_addPrescCommand == null)
                {
                    _addPrescCommand = new RelayCommand(NewPresc, CanCommandExecute);
                }
                return _addPrescCommand;
            }
            set { _addPrescCommand = value; }
        }

        /// <summary>
        /// indique si on doit fermer la fenêtre ou non
        /// </summary>
        public bool CloseSignal
        {
            get { return _closeSignal; }
            set
            {
                if (_closeSignal != value)
                {
                    _closeSignal = value;
                    OnPropertyChanged("CloseSignal");
                }
            }
        }


        /// <summary>
        /// Tension du patient
        /// </summary>
        public int BloodPressure
        {
            get { return _bloodPressure; }
            set { _bloodPressure = value; }
        }

        /// <summary>
        /// Commentaire sur le patient
        /// </summary>
        public string Comment
        {
            get { return _comment; }
            set { _comment = value; }
        }

        /// <summary>
        /// Poid du patient
        /// </summary>
        public int Weight
        {
            get { return _weight; }
            set { _weight = value; }
        }
        #endregion

        /// <summary>
        /// constructeur
        /// </summary>
        public AddObsViewModel(ref PatientServiceReference.Patient patient)
        {
            //init variables
            _prescriptions = new ObservableCollection<string>();
            _images = new ObservableCollection<Byte[]>();
            obs = new ObservationServiceReference.Observation();
            obs2 = new PatientServiceReference.Observation();
            serviceObservationClient = new ObservationServiceReference.ServiceObservationClient();
            _patient = patient;
        }

        /// <summary>
        /// Le bouton OK est-il accessible?
        /// </summary>
        /// <param name="parameter">Type Object</param>
        /// <returns>True</returns>
        private bool CanOk(object parameter)
        {
            return true;
        }

        #region fonctions
        /// <summary>
        /// Ajouter une prescription
        /// </summary>
        private void NewPresc(object parameter)
        {
            View.AddPrescView window = new View.AddPrescView();
            ViewModel.AddPrescViewModel vm = new ViewModel.AddPrescViewModel(ref obs2, ref obs, ref _prescriptions);

            window.DataContext = vm;
            window.Show();
        }

        /// <summary>
        /// Ajouter une Image
        /// </summary>
        private void NewImg(object parameter)
        {
            Byte[] FileInbytes;

            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "Images Sources (*.jpg, *.bmp, *.png)|*.jpg*;*.bmp*;*.png|All Files|*.*";
            dlg.Multiselect = false;

            if (dlg.ShowDialog() ?? false)
            {
                //open the file as a stream
                using (Stream s = dlg.OpenFile())
                {

                    // read s into a byte buffer.
                    FileInbytes = new Byte[s.Length];
                    int numBytesToRead = (int)s.Length;
                    int numBytesRead = 0;

                    while (numBytesToRead > 0)
                    {

                        // Read may return anything from 0 to numBytesToRead.
                        int n = s.Read(FileInbytes, numBytesRead, numBytesToRead);

                        // The end of the file is reached.
                        if (n == 0) break;

                        numBytesRead += n;
                        numBytesToRead -= n;

                    }
                    s.Close();

                    string sUploadedFileName = dlg.SafeFileName;

                    // Configure the message box to be displayed
                    string messageBoxText = "L'Image a bien été chargée ('" + sUploadedFileName + "' | " + numBytesRead + " octets)";
                    string caption = "Confirmation de l'Upload";
                    MessageBoxButton button = MessageBoxButton.OK;
                    MessageBoxImage icon = MessageBoxImage.Information;
                    // Display message box
                    MessageBoxResult result = MessageBox.Show(messageBoxText, caption, button, icon);

                    // Process message box results
                    if (result == MessageBoxResult.OK)
                    {
                        List<Byte[]> imgs = null;

                        if (obs.Pictures != null && obs.Pictures.Length > 0)
                            imgs = new List<Byte[]>(obs.Pictures);
                        else
                            imgs = new List<Byte[]>();

                        if (FileInbytes != null)
                        {
                            imgs.Add(FileInbytes);
                            _images.Add(FileInbytes);
                        }
                        obs.Pictures = imgs.ToArray();
                        obs2.Pictures = imgs.ToArray();
                    }
                }
            }

        }

        /// <summary>
        /// Valider l'ajout
        /// </summary>
        private void Confirm(object parameter)
        {
            obs.BloodPressure = BloodPressure;
            obs.Comment = Comment;
            obs.Weight = Weight;
            obs.Date = DateTime.Today;

            obs2.BloodPressure = BloodPressure;
            obs2.Comment = Comment;
            obs2.Weight = Weight;
            obs2.Date = DateTime.Today;
            try
            {
                serviceObservationClient.AddObservation(_patient.Id, obs);
            }
            catch
            {
            }
            List<PatientServiceReference.Observation> listObs = null;
            if (_patient.Observations != null)
                listObs = new List<PatientServiceReference.Observation>(_patient.Observations);
            else
                listObs = new List<PatientServiceReference.Observation>();
            listObs.Add(obs2);

            _patient.Observations = listObs.ToArray();
            CloseSignal = true;
        }
        #endregion fonctions
    }
}
